<template>
	<a-card :bordered="false" v-if="showIndex">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="5">
					<a-form-item label="开单时间" name="createTime">
						<a-range-picker v-model:value="searchFormState.createTime" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
					</a-form-item>
				</a-col>
				<a-col :span="7">
					<a-button type="default" @click="setDate('0')">今日</a-button>
					<a-button style="margin: 0 1px" @click="setDate('1')">昨日</a-button>
					<a-button style="margin: 0 1px" @click="setDate('2')">本周</a-button>
					<a-button style="margin: 0 1px" @click="setDate('3')">上周</a-button>
					<a-button style="margin: 0 1px" @click="setDate('4')">本月</a-button>
					<a-button style="margin: 0 1px" @click="setDate('5')">上月</a-button>
				</a-col>
<!--				<a-col :span="6">-->
<!--					<a-form-item label="业务类型" name="businessType">-->
<!--						<a-select v-model:value="searchFormState.businessType" placeholder="请选择业务类型"-->
<!--								  :options="businessTypeOptions"/>-->
<!--					</a-form-item>-->
<!--				</a-col>-->
				<a-col :span="4">
					<a-form-item label="退货单号" name="businessCode">
						<a-input v-model:value="searchFormState.businessCode" placeholder="请输入业务单号" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="供货单位" name="businessObjectId">
						<xn-page-select
							ref="xnbusinessObjectIdPageSelectRef"
							v-model:value="searchFormState.businessObjectId"
							placeholder="请选择供货单位"
							allow-clear
							show-search
							:page-function="businessObjectIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="经手人" name="businessHandlerId">
						<xn-page-select
							ref="xnbusinessHandlerIdPageSelectRef"
							v-model:value="searchFormState.businessHandlerId"
							placeholder="请选择经手人ID"
							allow-clear
							show-search
							:page-function="businessHandlerIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="采购员" name="businessSalesmanId">
						<xn-page-select
							ref="xnbusinessSalesmanIdPageSelectRef"
							v-model:value="searchFormState.businessSalesmanId"
							placeholder="请选择采购员ID"
							allow-clear
							show-search
							:page-function="businessSalesmanIdSelector"
						/>
					</a-form-item>
				</a-col>
<!--				<a-col :span="6" v-show="advanced">-->
<!--					<a-form-item label="出货门店" name="businessShippingStoreId">-->
<!--						<xn-page-select-->
<!--							ref="xnbusinessShippingStoreIdPageSelectRef"-->
<!--							v-model:value="searchFormState.businessShippingStoreId"-->
<!--							placeholder="请选择出货门店"-->
<!--							allow-clear-->
<!--							show-search-->
<!--							:page-function="businessShippingStoreIdSelector"-->
<!--						/>-->
<!--					</a-form-item>-->
<!--				</a-col>-->
<!--				<a-col :span="6" v-show="advanced">-->
<!--					<a-form-item label="出货仓库" name="businessShippingStorageId">-->
<!--						<xn-page-select-->
<!--							ref="xnbusinessShippingStorageIdPageSelectRef"-->
<!--							v-model:value="searchFormState.businessShippingStorageId"-->
<!--							placeholder="请选择出货仓库"-->
<!--							allow-clear-->
<!--							show-search-->
<!--							:page-function="businessShippingStorageIdSelector"-->
<!--						/>-->
<!--					</a-form-item>-->
<!--				</a-col>-->
				<a-col :span="4" v-show="advanced">
					<a-form-item label="退货门店" name="businessShippingStoreId">
						<xn-page-select
							ref="xnbusinessShippingStoreIdPageSelectRef"
							v-model:value="searchFormState.businessShippingStoreId"
							placeholder="请选择退货门店"
							allow-clear
							show-search
							:page-function="businessShippingStoreIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="承运人" name="businessCarrierId">
						<xn-page-select
							ref="xnbusinessCarrierIdPageSelectRef"
							v-model:value="searchFormState.businessCarrierId"
							placeholder="请选择承运人"
							allow-clear
							show-search
							:page-function="businessCarrierIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="结算状态" name="businessPaymentStatus">
						<a-select v-model:value="searchFormState.businessPaymentStatus"
								  placeholder="请选择结算状态"
								  allow-clear
								  :options="businessPaymentStatusOptions"/>
					</a-form-item>
				</a-col>
				<a-col :span="4" v-show="advanced">
					<a-form-item label="单据状态" name="businessStatus">
						<a-select v-model:value="searchFormState.businessStatus"
								  placeholder="请选择单据状态"
								  allow-clear
								  :options="businessStatusOptions"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'"/>
					</a>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="showForm()"
							  v-if="hasPerm('supplierPurchaseReturnAdd')">
						<template #icon>
							<plus-outlined/>
						</template>
						新增
					</a-button>
					<xn-batch-delete
						v-if="hasPerm('supplierPurchaseReturnBatchCancel')"
						:selectedRowKeys="selectedRowKeys"
						@batchDelete="cancelBatchSupplierPurchaseReturn"
						buttonName="批量作废"
						title="要作废这些单据吗"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'businessType'">
					{{ $TOOL.dictTypeData('SUPPLIER_BUSSINESS_TYPE', record.businessType) }}
				</template>
				<template v-if="column.dataIndex === 'businessPaymentStatus'">
					{{ record.businessPaymentStatus === '0' ? '未结算' : record.businessPaymentStatus === '1' ? '已结算' : '部分结算'}}
				</template>
				<template v-if="column.dataIndex === 'businessStatus'">
					<a-tag v-if="record.businessStatus === '0'" color="cyan">
						草稿
					</a-tag>
					<a-tag v-if="record.businessStatus === '1'" color="blue">
						已过账
					</a-tag>
					<a-tag v-if="record.businessStatus === '2'" color="purple">
						已作废
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="showForm(record)"
						   v-if="hasPerm('supplierPurchaseReturnEdit')">{{record.businessStatus === '0' ? '编辑' : '查看'}}</a>
						<a-divider type="vertical" v-show="record.businessStatus==='0'"
								   v-if="hasPerm(['supplierPurchaseReturnEdit', 'supplierPurchaseReturnCancel'], 'and')"/>
						<a-popconfirm title="确定要作废吗？" @confirm="cancelSupplierPurchaseReturn(record)">
							<a-button type="link" danger size="small" v-show="record.businessStatus==='0'"
									  v-if="hasPerm('supplierPurchaseReturnCancel')">作废
							</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form v-else ref="formRef" @successful="backIndex" @closed="closeForm"/>
</template>

<script setup name="supplierPurchaseReturn">
import tool from '@/utils/tool'
import {cloneDeep} from 'lodash-es'
import Form from './form.vue'
import supplierBusinessMainApi from '@/api/supplier/business/supplierBusinessMainApi'
import supplierSuppliersApi from "@/api/supplier/purchase/supplierSuppliersApi";
import supplierUserApi from "@/api/supplier/structure/supplierUserApi";
import supplierStoresApi from "@/api/supplier/base/supplierStoresApi";
import supplierStoragesApi from "@/api/supplier/warehouse/supplierStoragesApi";
import supplierCarrierApi from "@/api/supplier/base/supplierCarrierApi";
import {message} from "ant-design-vue";
import supplierObjectsApi from "@/api/supplier/custom/supplierObjectsApi";

const searchFormState = ref({})
const searchFormRef = ref()
const tableRef = ref()
const formRef = ref()
const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}
// 查询区域显示更多控制
const advanced = ref(false)
const toggleAdvanced = () => {
	advanced.value = !advanced.value
}
const showIndex = ref(true)
const showForm = (record)=> {
	showIndex.value = false
	nextTick(() => {
		formRef.value.onOpen(record)
	})
}
const closeForm = ()=> {
	backIndex()
	showIndex.value = true
}
const columns = [
	{
		title: '退货单号',
		dataIndex: 'businessCode'
	},
	{
		title: '供货单位',
		dataIndex: 'businessObjectIdName'
	},
	{
		title: '经手人ID',
		dataIndex: 'businessHandlerIdName',
		checked: false
	},
	{
		title: '业务员ID',
		dataIndex: 'businessSalesmanIdName',
		checked: false
	},
	{
		title: '退货门店',
		dataIndex: 'businessShippingStoreIdName'
	},
	{
		title: '退货仓库',
		dataIndex: 'businessShippingStorageIdName'
	},
	{
		title: '运单号',
		dataIndex: 'businessWaybillNumber',
		checked: false
	},
	{
		title: '合计件数',
		dataIndex: 'businessNumberProduction'
	},
	{
		title: '商品种类',
		dataIndex: 'businessNumberCategory'
	},
	{
		title: '包装方式',
		dataIndex: 'businessPackagingMethod',
		checked: false
	},
	{
		title: '承运人',
		dataIndex: 'businessCarrierIdName',
		checked: false
	},
	{
		title: '合计数量',
		dataIndex: 'businessTotalNumber'
	},
	{
		title: '合计金额',
		dataIndex: 'businessTotalAmount'
	},
	{
		title: '折让金额',
		dataIndex: 'businessDiscountAmount'
	},
	{
		title: '退货金额',
		dataIndex: 'businessPayableAmount'
	},
	{
		title: '实退金额',
		dataIndex: 'businessPayAmount'
	},
	{
		title: '待退金额',
		dataIndex: 'businessPendingAmount'
	},
	{
		title: '退款期限',
		dataIndex: 'businessPaymentDeadline',
		checked: false
	},
	{
		title: '结算状态',
		dataIndex: 'businessPaymentStatus'
	},
	{
		title: '单据状态',
		dataIndex: 'businessStatus'
	},
	{
		title: '整单备注',
		dataIndex: 'businessRemark',
		checked: false
	}
]
// 操作栏通过权限判断是否显示
if (hasPerm(['supplierPurchaseReturnEdit', 'supplierPurchaseReturnCancel'])) {
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 150
	})
}
const selectedRowKeys = ref([])
// 列表选择配置
const options = {
	// columns数字类型字段加入 needTotal: true 可以勾选自动算账
	alert: {
		show: false,
		clear: () => {
			selectedRowKeys.value = ref([])
		}
	},
	rowSelection: {
		onChange: (selectedRowKey, selectedRows) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}
const loadData = (parameter) => {
	const searchFormParam = cloneDeep(searchFormState.value)
	if (searchFormParam.createTime) {
		searchFormParam.startCreateTime = searchFormParam.createTime[0]
		searchFormParam.endCreateTime = searchFormParam.createTime[1]
		delete searchFormParam.createTime
		searchFormParam.businessType = "RE"
		return supplierBusinessMainApi.supplierBusinessMainPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}else{
		if (searchFormParam.createTime ===null){
			message.warn("请确定时间范围")
		}
		return Promise.resolve(null)
	}

}
// 重置
const reset = () => {
	searchFormRef.value.resetFields()
	setDate('0')
	tableRef.value.refresh(true)
}
// 删除
const cancelSupplierPurchaseReturn = (record) => {
	let params = [
		{
			id: record.id
		}
	]
	supplierBusinessMainApi.supplierBusinessMainCancel(params).then(() => {
		tableRef.value.refresh(true)
	})
}
// 批量删除
const cancelBatchSupplierPurchaseReturn = (params) => {
	supplierBusinessMainApi.supplierBusinessMainCancel(params).then(() => {
		tableRef.value.clearRefreshSelected()
	})
}
const xnbusinessObjectIdPageSelectRef = ref();
const businessObjectIdSelector = (param) => {
	return supplierObjectsApi.supplierObjectsPage(Object.assign(param, {objectType:'0'})).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.objectName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const xnbusinessHandlerIdPageSelectRef = ref();
const businessHandlerIdSelector = (param) => {
	return supplierUserApi.userPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.name,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}

const xnbusinessSalesmanIdPageSelectRef = ref();
const businessSalesmanIdSelector = (param) => {
	return supplierUserApi.userPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.name,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}

// const xnbusinessShippingStoreIdPageSelectRef = ref();
// const businessShippingStoreIdSelector = (param) => {
// 	return supplierStoresApi.supplierStoresPage(param).then((data) => {
// 		if (data.records) {
// 			data.records = data.records.map((item) => {
// 				return {
// 					name: item.storeName,
// 					id: item.id,
// 				};
// 			});
// 		}
// 		return Promise.resolve(data)
// 	})
// }
// nextTick(() => {
// 	xnbusinessShippingStoreIdPageSelectRef.value.onPage({current: 1});
// });
// const xnbusinessShippingStorageIdPageSelectRef = ref();
// const businessShippingStorageIdSelector = (param) => {
// 	return supplierStoragesApi.supplierStoragesPage(param).then((data) => {
// 		if (data.records) {
// 			data.records = data.records.map((item) => {
// 				return {
// 					name: item.storeName,
// 					id: item.id,
// 				};
// 			});
// 		}
// 		return Promise.resolve(data)
// 	})
// }
// nextTick(() => {
// 	xnbusinessShippingStorageIdPageSelectRef.value.onPage({current: 1});
// });
const xnbusinessShippingStoreIdPageSelectRef = ref();
const businessShippingStoreIdSelector = (param) => {
	return supplierStoresApi.supplierStoresPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.storeName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}

const xnbusinessCarrierIdPageSelectRef = ref();
const businessCarrierIdSelector = (param) => {
	return supplierCarrierApi.supplierCarrierPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.carrierName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}

const businessPaymentStatusOptions = [{label:'未结算',value:'0'},{label:'已结算',value:'1'},{label:'部分结算',value:'2'}]
const businessStatusOptions = tool.dictList('BUSINESS_STATUS')
const setDate = (index) => {
	switch (index) {
		case '0':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break

		case '1':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(Date.now() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(Date.now() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
		case '2':
			var dateArray = []
			dateArray[0] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() + 1),
				'{y}-{m}-{d}'
			)
			dateArray[1] = tool.parseTime(
				new Date(
					new Date().getFullYear(),
					new Date().getMonth(),
					new Date(
						new Date().getFullYear(),
						new Date().getMonth(),
						new Date().getDate() - new Date().getDay()
					).getDate() + 7
				),
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '3':
			var dateArray = []
			dateArray[0] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() - 6),
				'{y}-{m}-{d}'
			)
			dateArray[1] = tool.parseTime(
				new Date(
					new Date().getFullYear(),
					new Date().getMonth(),
					new Date(
						new Date().getFullYear(),
						new Date().getMonth(),
						new Date().getDate() - new Date().getDay()
					).getDate()
				),
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '4':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - 1,
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '5':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1) - 1, '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
		default:
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
	}
}
nextTick(()=>{
	setDate('0')
	backIndex()
})
const backIndex = () => {
	nextTick(() => {
		xnbusinessCarrierIdPageSelectRef.value.onPage({current: 1});
		xnbusinessShippingStoreIdPageSelectRef.value.onPage({current: 1});
		xnbusinessSalesmanIdPageSelectRef.value.onPage({current: 1});
		xnbusinessHandlerIdPageSelectRef.value.onPage({current: 1});
		xnbusinessObjectIdPageSelectRef.value.onPage({current: 1});
		tableRef.value.refresh()
	})
}
</script>
